package com.yhd.tomcat.handler.service;

import com.yhd.tomcat.Bootstrap;
import com.yhd.tomcat.handler.Handler;
import com.yhd.tomcat.req.BaseRequest;
import com.yhd.tomcat.req.HttpRequest;
import com.yhd.tomcat.resp.BaseResponse;
import com.yhd.tomcat.resp.HttpResponse;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author yhd
 * @email yinhuidong1@xiaomi.com
 * @description TODO
 * @since 2021/6/10 下午5:44
 */
public class ServiceHandler extends Handler {

    private static volatile ServiceHandler serviceHandler;

    private ServiceHandler() {
    }

    public static ServiceHandler getSingleton(){
        if (serviceHandler==null){
            synchronized (Bootstrap.class){
                if (serviceHandler==null){
                    serviceHandler=new ServiceHandler();
                }
            }
        }
        return serviceHandler;
    }

    public void process(Socket client) throws Exception {
        InputStream inputStream = client.getInputStream();
        OutputStream outputStream = client.getOutputStream();
        BaseRequest request = new HttpRequest(inputStream);
        BaseResponse response = new HttpResponse(outputStream);
        String url = request.getUrl();

        System.out.println("从容器获取对应的事件处理器Servlet，执行事件");
        if (servletMap.containsKey(url))
            servletMap.get(url).service(request, response);
        else
            response.write("404 Not Found");
        outputStream.flush();
        outputStream.close();
        inputStream.close();


    }
}
